package com.tanhua.sso.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.utils.sendmsgutils;
import com.tanhua.sso.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    private Result result;
    @PostMapping("login")
    public ResponseEntity<Result> sendCheckCode(@RequestBody Map<String, String> param) {
        String phone = param.get("phone");
        try {
            result= userService.sendCheckCode(phone);
            if (null == result) {
                return ResponseEntity.ok(null);
            }
        } catch (Exception e) {
            log.error("发送短信验证码失败~ phone = " + phone, e);
            result = result.builder().code("000002").msg("短信验证码发送失败！").build();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
    }
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){
        try {
            String phone = param.get("phone");
            String code = param.get("verificationCode");

            String data = this.userService.login(phone, code);
            if(StringUtils.isNotEmpty(data)){
                //登录成功
                Map<String, Object> result = new HashMap<>(2);
                String[] ss = StringUtils.split(data, "|");

                result.put("token", ss[0]);
                result.put("isNew", Boolean.valueOf(ss[1]));
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
         result = result.builder().code("000002").msg("登录失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
    }

    @GetMapping("{token}")
    public User findUserbytoken(@PathVariable("token") String token){
        return userService.findUserbytoken(token);
    }
}
